package com.qfedu.common.core.utils;

import io.jsonwebtoken.Claims;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class TokenUtils {

    /**
     * 通过token获取用户id
     *
     * @return
     */
    public static Integer getUidFromToken() {
        // 动态获取HttpServletRequest对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String token = request.getHeader("Token");
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("token不存在");
        }
        Claims claims = JwtUtils.parseJWT(token);
        Object uid = claims.get("uid");
        return Integer.valueOf(uid.toString());
    }
}
